﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace TestSinaAPI
{
    class Program
    {
        static void Main(string[] args)
        {
            var comeon = Convert.ToBase64String(new ASCIIEncoding().GetBytes("huangguan3112789@gmail.com" + ":" + "3133661"));
            Console.WriteLine(comeon);

            string getUrl = "http://api.t.sina.com.cn/statuses/friends_timeline.json?source=3476523072&page=1";
            var returnValue = ReadXMLDataToString(getUrl);
            Console.WriteLine(returnValue);

            var testData = "source=3476523072&status=去搞定 测试一下呗";
            string postUrl = "http://api.t.sina.com.cn/statuses/update.json";
            var isSucc= PostBlog(postUrl, testData);
            Console.WriteLine(isSucc);
            Console.ReadKey();
        }

        internal static bool PostBlog(string url, string data)
        {
            try
            {
                HttpWebRequest request2 = WebRequest.Create(url) as HttpWebRequest;
                CredentialCache cache = new CredentialCache();
                cache.Add(new Uri(url), "Basic", new NetworkCredential("ygd.weibo.superwolf@gmail.com", "superwolf"));
                request2.Credentials = cache;
                request2.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes("ygd.weibo.superwolf@gmail.com:superwolf")));
                request2.Method = "POST";
                request2.ContentType = "application/x-www-form-urlencoded";
                byte[] bytes = Encoding.UTF8.GetBytes(data);
                request2.ContentLength = bytes.Length;
                Stream requestStream = request2.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        internal static string ReadXMLDataToString(string url)
        {
            CredentialCache cache = new CredentialCache();
            cache.Add(new Uri(url), "Basic", new NetworkCredential("ygd.weibo.superwolf@gmail.com", "superwolf"));
            WebRequest request = WebRequest.Create(url);
            request.Credentials = cache;
            request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes("ygd.weibo.superwolf@gmail.com:superwolf")));
            WebResponse response = request.GetResponse();
            string str = null;
            using (Stream stream = response.GetResponseStream())
            {
                str = new StreamReader(stream, Encoding.UTF8).ReadToEnd();
            }
            response.Close();
            return str;
        }
    }
}
